package com.woniu.config;

import com.woniu.outlet.dao.MessageMapper;
import com.woniu.util.MessageStatus;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfig {

    @Autowired
    private MessageMapper messageMapper;

    @Bean
    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(connectionFactory);

        //设置回调
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean flag, String cause) {
                if(flag){
                    com.woniu.outlet.po.Message message1 = messageMapper.selectByPrimaryKey(Long.parseLong(correlationData.getId()));
                    if(!message1.getStatus().equals(MessageStatus.ROUTE_ERROR.getStatus())){  //队列也路由正确
                        //message表
                        //把状态改成已发送
                        message1.setStatus(MessageStatus.SENDED.getStatus());
                        messageMapper.updateByPrimaryKeySelective(message1);
                    }
                }
            }
        });

        //1.如果交换机成功了，队列也成功了，
        //2.如果交换机成功了，但是路由到队列失败了，则先执行setReturnCallback 再执行setConfirmCallback
        template.setMandatory(true);
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                String correlationId = message.getMessageProperties().getCorrelationId();

                //修改该消息的状态为路由错误
                com.woniu.outlet.po.Message message1 = new com.woniu.outlet.po.Message();
                message1.setId(Long.parseLong(correlationId));
                //设置路由状态为路由失败
                message1.setStatus(MessageStatus.ROUTE_ERROR.getStatus());
                messageMapper.updateByPrimaryKeySelective(message1);
            }
        });

        return template;

    }
}
